#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
static int get_random_data(void* ptr, size_t size_ptr, size_t* size);
int main(int argc, char* argv[])
{
    if(2 != argc) {
        printf("usage : writef filename.\n");
        return -1;
    }

    setbuf(stdout, NULL);

    #define LEN (1024*1024)
    void* ptr = malloc(LEN);

    FILE* fp = fopen(argv[1], "w");
    if(NULL == fp) {
        printf("fopen (%s) error.\n", argv[1]);
        return -1;
    }

    size_t size = 0;
    size_t total = 0;
    int n;
    while(1) {
        get_random_data(ptr, LEN, &size);
#if 1
        n = fwrite(ptr, 1, size, fp);
        if(n != size) {
            printf("fwrite error.\n");
            break;
        }
#endif
        total += size;

        printf("+%6u total : %u\n", size, total);
        //sleep(1);
    }

    fclose(fp);

    return 0;
}


int urand(void)
{
    int ret;

    struct timeval tv;
    gettimeofday(&tv, NULL);

    srand(tv.tv_sec + tv.tv_usec);
    ret = rand();
    //printf("ret = %d.\n", ret);

    return (ret);
}


int urandft(int f, int t)
{
    int ret;

    ret = urand();
    ret = f + ret%(t-f+1);

    return(ret);
}


int get_random_data(void* ptr, size_t size_ptr, size_t* size)
{
    size_t rsize = urandft(1, size_ptr-1);
    *size = rsize;

    int i;
    for(i=0; i<rsize/1024; i++) {
        memset(ptr+(i*1024), urandft(0, 255), 1024);
    }

    return 0;
}
